﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Security.Cryptography;

namespace GestorDeFlotasDesktop.AbmUsuario
{
    public partial class AbmUsuario : MasterPage
    {
        Form Ventana_Padre;
        ArrayList array = new ArrayList();
        ArrayList arrayRol = new ArrayList();
        ArrayList ids = new ArrayList();
        DataTable usuarios;
        DataTable usuariosErrores;
        DataTable copiaUsers;
        int activo;
        public capaDatos.SQLSyntaxisGeneration usuariosCD = new capaDatos.SQLSyntaxisGeneration();
      
        public AbmUsuario(Form ventaPadre)
        {
            InitializeComponent();
            initialize(ventaPadre, ref Ventana_Padre);
            
            Ventana_Padre.Visible = false;

           
        }
     
        private void AbmUsuario_Load(object sender, EventArgs e)
        {
            txtPassword.Visible = false;
            lblPassword.Visible = false;
            dataGridView2.Visible = false;
            dataGridView2.ReadOnly = true;
            btAlta.Text = "Alta";
            BTBaja.Text = "Baja";
            activo = 1;
            textBox2.Visible = false;
            textBox2.Text = "";
            textBox3.Visible = false;
            textBox3.Text = "";
            label2.Visible = false;
            label3.Visible = false;
        }

        private void AbmUsuario_FormClosing(object sender, FormClosingEventArgs e)
        {
             Ventana_Padre.Visible = true;
        } 

        private void btAlta_Click(object sender, EventArgs e)
        {
            
            if (btAlta.Text == "Confirmar" && BTBaja.Text == "Cancelar" && textBox1.Visible)//si veo el nombre es para un alta
            {
                if (textBox1.Text == "" || txtPassword.Text == ""||textBox2.Text==""||textBox3.Text=="")
                    MessageBox.Show("Todos los campos son obligatorios. Por favor complete los campos faltantes.", "ABM Usuarios - Alta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                else
                {
                 
                    ArrayList parametros = new ArrayList();

                    parametros = parametrosStoredProcedure(paramsNames("nombre", "pass", "preg", "rta"), paramsValues(textBox1.Text, BitConverter.ToString(encriptar(txtPassword.Text)), textBox2.Text, BitConverter.ToString(encriptar(textBox3.Text))));

                    usuariosErrores = usuariosCD.executeSp("[PELUSA].insertarDatosUsuario",parametros);
                   string result = Convert.ToString(usuariosErrores.Rows[0].ItemArray[0]);
                    if ( result!= "ok")
                    {

                        MessageBox.Show("El nombre de usuario solicitado ya se encuentra en uso.", "ABM Usuarios - Alta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    }
                    else
                    {
                        string query = "select idUsuario from PELUSA.usuarios where usernameUsuario ='" + textBox1.Text + "'";
                        DataTable aux = usuariosCD.executeQuery(query);
                        int id = Convert.ToInt32(aux.Rows[0].ItemArray[0]); //id del usuario creado

                        if (arrayRol.Count != 0)//puedo insertar un usuario sin roles
                        {

                            int[] lista = new int[arrayRol.Count];
                            arrayRol.CopyTo(lista);

                            foreach (int i in lista)
                            {
                                ArrayList param = new ArrayList();

                                param = parametrosStoredProcedure(paramsNames("id", "idrol"), paramsValues(id, Convert.ToInt32(copiaUsers.Rows[i].ItemArray[0])));


                                usuariosCD.executeSp("[PELUSA].asignarRoles", param);

                            }
                        }

                        txtPassword.Visible = false;
                        lblPassword.Visible = false;
                        dataGridView2.Visible = false;
                        dataGridView2.ReadOnly = true;
                        btAlta.Text = "Alta";
                        BTBaja.Text = "Baja";
                        textBox1.Visible = true;
                        textBox1.Text = "";
                        label1.Visible = true;
                        dataGridView1.Visible = true;
                        dataGridView1.ReadOnly = false;
                        BtbBuscar.Visible = true;
                        textBox2.Visible = false;
                        textBox2.Text = "";
                        textBox3.Visible = false;
                        textBox3.Text = "";
                        label2.Visible = false;
                        label3.Visible = false;
                    }

                }

            }
             else if (btAlta.Text == "Confirmar" && BTBaja.Text == "Cancelar" && !textBox1.Visible &&array.Count!=0) {
                    //aca es una modificacion
                 if (txtPassword.Text != "")
                 {
        

                     //SHA256Managed password = new SHA256Managed();
                     //byte[] texto = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text);
                     //byte[] textocifrado = password.ComputeHash(texto);

                     usuariosCD.executeSp("[PELUSA].cambiarPassword", parametrosStoredProcedure(paramsNames("id", "pass"), paramsValues(Convert.ToInt32(ids[0]), BitConverter.ToString(encriptar(txtPassword.Text)))));

                 }
                 int n = Convert.ToInt32(array[array.Count - 1].ToString());
                 
                 if (chUserHab.Checked && activo == 0)
                 {//quiere rehabilitar usuario

                     usuariosCD.executeSp("PELUSA.inhabilitarHabilitarUsuario", parametrosStoredProcedure(paramsNames("id", "valor"), paramsValues(Convert.ToInt32(ids[0]), 1)));
                     chUserHab.Checked = true;
                 }
                 if(!chUserHab.Checked && activo == 1){
                     MessageBox.Show("No se permite deshabilitar usuarios desde la modificación. Para inhabilitar un usuario, presione el botón de Baja");
                 
                 }
                 int i;
                 for (i = 0; i < usuarios.Rows.Count; i++)
                 {
                    if(arrayRol.Contains(i))
                        usuariosCD.executeSp("[PELUSA].asignarRoles", parametrosStoredProcedure(paramsNames("id", "rol"), paramsValues(Convert.ToInt32(ids[0]), Convert.ToInt32(usuarios.Rows[i].ItemArray[0]))));

                    else
                        usuariosCD.executeSp("[PELUSA].quitarRoles", parametrosStoredProcedure(paramsNames("id", "rol"), paramsValues(Convert.ToInt32(ids[0]), Convert.ToInt32(usuarios.Rows[i].ItemArray[0]))));


                 }
                 ids.Remove(ids[0]);
                 txtPassword.Visible = false;
                 lblPassword.Visible = false;
                 dataGridView2.Visible = false;
                 dataGridView2.ReadOnly = true;
                 btAlta.Text = "Alta";
                 BTBaja.Text = "Baja";
                 textBox1.Visible = true;
                 textBox1.Text = "";
                 label1.Visible = true;
                 dataGridView1.Visible = true;
                 dataGridView1.ReadOnly = false;
                 BtbBuscar.Visible = true;
                 dataGridView1.ClearSelection();
                 dataGridView2.ClearSelection();
             }

            else if (btAlta.Text == "Deshabilitar" && BTBaja.Text == "Cancelar" && textBox1.Visible)
            {//estoy en una baja
                int n = Convert.ToInt32(arrayRol[arrayRol.Count-1].ToString());
                usuariosCD.executeSp("PELUSA.inhabilitarHabilitarUsuario", parametrosStoredProcedure(paramsNames("id", "valor"), paramsValues(Convert.ToInt32(usuarios.Rows[n].ItemArray[0]), 0)));
                txtPassword.Visible = false;
                lblPassword.Visible = false;
                dataGridView2.Visible = false;
                dataGridView2.ReadOnly = true;
                btAlta.Text = "Alta";
                BTBaja.Text = "Baja";
                textBox1.Visible = true;
                label1.Visible = true;
                dataGridView1.Visible = true;
                dataGridView1.ReadOnly = false;
                chUserHab.Visible = true;
            }
            else //estoy en un alta 1era parte
            {
                label2.Visible = true;
                label3.Visible = true;
                textBox2.Visible = true;
                textBox2.Text = "";
                textBox3.Visible = true;
                textBox3.Text = "";
                btAlta.Text = "Confirmar";
                BTBaja.Text = "Cancelar";

                string query = "select r.idRol 'Id del rol', r.nombreRol as 'Nombre del rol'";
                query += " from [PELUSA].roles r where r.activoRol=1";//sólo muestra roles activos

                usuarios = usuariosCD.executeQuery(query);
                this.dataGridView2.DataSource = usuarios;
                this.dataGridView2.AutoResizeColumns();
                dataGridView1.ReadOnly = true;
                dataGridView1.Visible = false;
                dataGridView2.Visible = true;
               dataGridView2.ReadOnly = false;
                BtbBuscar.Visible = false;
                txtPassword.Visible = true;
                lblPassword.Visible = true;
                chUserHab.Visible = true;
                copiaUsers = usuarios;
            }
            dataGridView1.DataSource = "";
        }
        private void BTBaja_Click(object sender, EventArgs e)
        {

            if (BTBaja.Text == "Cancelar")
            {
                panel2.Visible = false;
              
                dataGridView2.Visible = false;
                dataGridView2.ReadOnly = true;
                btAlta.Text = "Alta";
                BTBaja.Text = "Baja";
                textBox1.Visible = true;
                label1.Visible = true;
                dataGridView1.Visible = true;
                dataGridView1.ReadOnly = false;
                BtbBuscar.Visible = true;
                dataGridView1.DataSource = "";
                
            }
            else { //esto es una baja.

                {
                    
                string query = "select idUsuario 'Id del Usuario', usernameUsuario as 'Nombre del Usuario'";
                query += " from [PELUSA].Usuarios";
                usuarios = usuariosCD.executeQuery(query);
                this.dataGridView2.DataSource = usuarios;
                this.dataGridView2.AutoResizeColumns();
                txtPassword.Visible = false;
                lblPassword.Visible = false;
                dataGridView2.Visible = true;
                dataGridView2.ReadOnly = false;
                btAlta.Text = "Deshabilitar";
                BTBaja.Text = "Cancelar";
                textBox1.Visible = true;
                label1.Visible = true;
                dataGridView1.Visible = false;
                dataGridView1.ReadOnly = true;
                chUserHab.Visible = false;
                }
            }
            
        }



     


        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && usuarios.Rows.Count > e.RowIndex)
            {
                if (btAlta.Text == "Confirmar" || BTBaja.Text == "Cancelar" && array.Count != 0)
                {

                    string idUser = Convert.ToString(usuarios.Rows[e.RowIndex].ItemArray[0]);
                    ids.Add(Convert.ToInt32(usuarios.Rows[e.RowIndex].ItemArray[0]));

                    activo = Convert.ToInt32(usuarios.Rows[e.RowIndex].ItemArray[3]);
                    string query = "select distinct r.idRol as 'id del rol', r.nombreRol as 'Nombre del rol', cast(isnull((select 1 from [PELUSA].roles_usuarios ru1 where ru1.idRol= r.idRol and ru1.idUsuario =";
                    query += idUser;
                    query += "),0) as bit) as 'Roles asignados actualmente' from [PELUSA].roles_usuarios ru, [PELUSA].roles r where ";
                    query += "r.idRol=ru.idRol";
                    dataGridView1.ReadOnly = true;
                    dataGridView1.Visible = false;
                    dataGridView2.Visible = true;
                    dataGridView2.ReadOnly = true;
                    dataGridView2.BringToFront();
                    this.dataGridView2.DataSource = usuariosCD.executeQuery(query);
                    this.dataGridView2.AutoResizeColumns();

                    modificarDatosUser( Convert.ToInt64(idUser) );
                    chUserHab.Visible = true;
                    if (activo == 1)
                        chUserHab.Checked = true;
                    else
                        chUserHab.Checked = false;
                   
                }

                BTBaja.Visible = true;
                btAlta.Visible = true;

                //textBox1.Visible = false;
                //label1.Visible = false;
                //BtbBuscar.Visible = false;
                //lblPassword.Visible = true;
                //txtPassword.Visible = true;
            }
        }

        private void modificarDatosUser( Int64  idUser)
        {
            lblPassword.Visible = true;
            txtPassword.Visible = true;
            label2.Visible = true;
            textBox2.Visible = true;
            label3.Visible = true;
            textBox1.Visible = true;
            label1.Visible = true;
            textBox3.Visible = true;

            DataTable dt;
            dt = usuariosCD.executeQuery(" select usernameUsuario  from PELUSA.usuarios where idUsuario =" + idUser);
            textBox1.Text = Convert.ToString ( dt.Rows[0].ItemArray[0]);
            textBox1.ReadOnly = true;

            BtbBuscar.Text = "enviar";

      }
        private void BtbBuscar_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
            if (BtbBuscar.Text == "enviar")
            {      
                BtbBuscar.Text = "Buscar";
                if (txtPassword.Text != "" & textBox2.Text != "" & textBox3.Text != "")
                {    


                    string passEncr = BitConverter.ToString(encriptar(txtPassword.Text));
                    string rstaEnc = BitConverter.ToString(encriptar(textBox3.Text));
                    ArrayList param = new ArrayList();
                    param = parametrosStoredProcedure(paramsNames("pasw", "preg", "rsta"), paramsValues(passEncr, textBox2.Text, rstaEnc));
                    usuariosCD.executeSp("PELUSA.updateUser", param);
               
                }
            }
            
            
            if (dataGridView1.Visible)
            {
                string query = "select distinct u.idUsuario as 'Id Usuario',u.usernameUsuario as 'Usuario',r.nombreRol as 'Nombre del rol',activoUsuario as 'Usuario activo' from [PELUSA].usuarios u, [PELUSA].roles_usuarios ru, [PELUSA].roles r";
                if (textBox1.Text != "")
                {
                    query += " where u.usernameUsuario like '%" + textBox1.Text + "%' and u.idUsuario = ru.idUsuario and r.idRol=ru.idRol order by u.idUsuario";
                }
                

                usuarios = usuariosCD.executeQuery(query);
                this.dataGridView1.DataSource = usuarios;

                textBox1.Visible = true;
            }
            else {
                string query = "select u.idUsuario as 'Id Usuario',u.usernameUsuario as 'Usuario' from [PELUSA].usuarios u";
                if (textBox1.Text != "")
                {
                    query += " where u.usernameUsuario like '%" + textBox1.Text + "%'";
                }


                usuarios = usuariosCD.executeQuery(query);
                this.dataGridView2.DataSource = usuarios;

                textBox1.Visible = true;
            
            }
         
        }

        private void btLimpiar_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            txtPassword.Text = "";
            panel2.Visible = false;
            //para destildar todas las opciones seleccionadas de roles
            if (arrayRol.Count != 0) {
               
                int [] lista= new int[arrayRol.Count];
                arrayRol.CopyTo(lista);
               
                foreach (int i in lista){
                     setearCheckBox(i, arrayRol, dataGridView2, null, btAlta);
         
                }
            
            }

        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((btAlta.Text == "Confirmar" || btAlta.Text == "Deshabilitar") && BTBaja.Text == "Cancelar" && e.RowIndex >= 0 && e.RowIndex < dataGridView2.RowCount)
            {
                int baja=0;
                if(btAlta.Text == "Deshabilitar")
                    baja=1;
                setearCheckBox(e.RowIndex, arrayRol, dataGridView2, null, btAlta);
                if (baja == 1)
                    btAlta.Text = "Deshabilitar";

            }
        }

       

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0)
            {  
            setearCheckBox(e.RowIndex, array, dataGridView1, null, btAlta);
            btAlta.Text = "Confirmar";
            BTBaja.Text = "Cancelar";
            textBox1.Visible = false;

            }
        }

  

       

      
    }
}
